package mark.tom.sail;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.JobManager;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.birbit.android.jobqueue.config.Configuration;

import static mark.tom.sail.Util.log_i;

public class JobManagerCollector implements RecordCollector {

    private JobManager jobManager;
    private final Context mContext;

    public JobManagerCollector(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void doInBackground(@NonNull String generatorFileName,
                               @NonNull String convertedData,
                               @NonNull FileStorage fileStorage,
                               @NonNull LogInterceptor logInterceptor) {
        getJobManager().addJobInBackground(new AnalyticsCollectJob(generatorFileName, convertedData, fileStorage, logInterceptor));
    }

    private final static class AnalyticsCollectJob extends Job {

        private final FileStorage fileStorage;
        private final LogInterceptor logInterceptor;
        private final String generatorFileName;
        private final String convertedData;

        AnalyticsCollectJob(@NonNull String generatorFileName,
                            @NonNull String convertedData,
                            @NonNull FileStorage fileStorage,
                            @NonNull LogInterceptor logInterceptor) {
            super(new Params(500).groupBy("Sail"));
            this.fileStorage = fileStorage;
            this.generatorFileName = generatorFileName;
            this.convertedData = convertedData;
            this.logInterceptor = logInterceptor;
        }

        @Override public void onAdded() {
            log_i(logInterceptor, "Job Added And FileName is " + generatorFileName + " FileContent is " + convertedData);
        }

        @Override public void onRun() {
            fileStorage.saveLogContent(generatorFileName, convertedData);
            log_i(logInterceptor, "Job Run And Data Has Been Saved");
        }

        @Override protected void onCancel(int cancelReason, @Nullable Throwable throwable) {

        }

        @Override protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
            return RetryConstraint.createExponentialBackoff(runCount, 1000);
        }
    }

    private JobManager getJobManager() {
        if (null == jobManager) {
            Configuration.Builder builder = new Configuration.Builder(mContext)
                    .minConsumerCount(1)        // always keep at least one consumer alive
                    .maxConsumerCount(3);        // up to 3 consumers at a time
            jobManager = new JobManager(builder.build());
        }
        return jobManager;
    }
}
